package com.zhsj.OkeHomeConsumption.ui.activity.wallet;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.BankMessage;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeChecker;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.utils.Arith;
import com.zhsj.OkeHomeConsumption.utils.JsonUtils;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by zwj on 2017/10/17.
 * 提现 -- 个人钱包用户
 */

public class ExtractMoneyFragment extends BaseFragment implements View.OnClickListener{

    /**
     * 计时器
     */
    private TimeChecker timeChecker = null;
    /**
     * 实例化ProgressDrawableAlertDialog
     */
    private ProgressDrawableAlertDialog pDialogUtils = null;
    //左标题
    private TextView topbar_textview_leftitle;
    //标题
    private TextView topbar_textview_title;
    //银行卡号
    private TextView bankno_text;
    //提现余额
    private ClearEditText money_text;
    //当前余额
    private TextView balance_describe;
    //全部提取
    private TextView all_extract;
    //提现
    private TextView extract_money;

    //银行信息
    private BankMessage bankMessage;

    //钱包余额
    private String walletBalanceStr;

    private FormalUserInfo userInfo;
    //判断是否是首次  true是首次
    private boolean isFirstFree;

    //当前余额
    private Double nowMoney;
    //提现金额
    private Double extractMonry;

    //银行名称
    private TextView bankname_text;
    //银行卡列表
//    private List<BankMessage> mBankMessageList;

    //忘记密码
    private TextView password_forget_text;

    //用户所属商户号
    private String oid_partner;

    public static ExtractMoneyFragment newInstance(FormalUserInfo userInfo, BankMessage bankMessage, String walletBalanceStr, String oid_partner) {
        Bundle args = new Bundle();
        ExtractMoneyFragment fragment = new ExtractMoneyFragment();
        args.putSerializable("userInfo", userInfo);
        args.putSerializable("bankMessage", bankMessage);
        args.putString("walletBalanceStr", walletBalanceStr);
        args.putString("oid_partner", oid_partner);
        fragment.setArguments(args);
        return fragment;
    }



    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userInfo = (FormalUserInfo) getArguments().getSerializable("userInfo");
        bankMessage = (BankMessage) getArguments().getSerializable("bankMessage");
        walletBalanceStr = getArguments().getString("walletBalanceStr");
        oid_partner = getArguments().getString("oid_partner");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_extractmoney, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initListener();
        isFirstFree();
//        getBankList(userInfo.getId() + "", "RSA");
        setData();
    }

    private void initView(View view){
        topbar_textview_leftitle = (TextView) view.findViewById(R.id.topbar_textview_leftitle);
        topbar_textview_leftitle.setVisibility(View.VISIBLE);
        topbar_textview_title = (TextView) view.findViewById(R.id.topbar_textview_title);
        topbar_textview_title.setText("提现");
        bankno_text = (TextView) view.findViewById(R.id.bankno_text);
        money_text = (ClearEditText) view.findViewById(R.id.money_text);
        all_extract = (TextView) view.findViewById(R.id.all_extract);
        balance_describe = (TextView) view.findViewById(R.id.balance_describe);
        extract_money = (TextView) view.findViewById(R.id.extract_money);
        bankname_text = (TextView) view.findViewById(R.id.bankname_text);
        password_forget_text = (TextView) view.findViewById(R.id.password_forget_text);
        password_forget_text.setOnClickListener(this);
    }

    private void initListener(){
        timeChecker = new TimeChecker(TimeOutHandler.timeOutHandler, Constants.TIME_OUT);
        pDialogUtils = new ProgressDrawableAlertDialog(_mActivity);
        topbar_textview_leftitle.setOnClickListener(this);
        all_extract.setOnClickListener(this);
        extract_money.setOnClickListener(this);
    }


    /**
     * 设置数据
     */
    private void setData(){
        if (bankMessage != null){
            balance_describe.setText(String.format(getResources().getString(R.string.balance), walletBalanceStr));
            bankname_text.setText(bankMessage.getBank_name());
            bankno_text.setText("**** **** **** " + bankMessage.getCard_no());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.topbar_textview_leftitle:
                _mActivity.onBackPressed();
                break;
            case R.id.all_extract:
                //全部提现
                money_text.setText(walletBalanceStr);//13934956217
                break;
            case R.id.extract_money:
//                //提现
                if (TextUtils.isEmpty(money_text.getText().toString().trim())){
                    showShortToast("请输入提现金额");
                    return;
                }
                nowMoney = Double.parseDouble(walletBalanceStr);
                extractMonry = Double.parseDouble(money_text.getText().toString().trim());
                if (extractMonry < 20.00){
                    showShortToast("提现金额需大于等于20元");
                    return;
                }
                if (nowMoney >= extractMonry){
                    showMoneyDialog();
                }else {
                    showShortToast("提取金额不能大于钱包余额");
                }
                break;
            case R.id.password_forget_text:
                //忘记密码
                start(PasswordForgetFragment.newInstance(userInfo, oid_partner));
                break;
        }
    }

    /**
     * 当前提现金额
     */
    private DecimalFormat df;
    private void showMoneyDialog(){
        LayoutInflater factory = LayoutInflater.from(getActivity());
        final LinearLayout dialogView = (LinearLayout) factory.inflate(
                R.layout.dialog_makesure_extract_money, null);
        //金额
        final TextView money_amount_text = (TextView) dialogView.findViewById(R.id.money_amount_text);
        //描述
        final TextView money_describe_text = (TextView) dialogView.findViewById(R.id.money_describe_text);
        //实际到账金额
        final TextView money_practice_amount_text = (TextView) dialogView.findViewById(R.id.money_practice_amount_text);
        //取消
        final TextView cancle_text = (TextView) dialogView.findViewById(R.id.cancle_text);
        //确认提现
        final TextView make_sure_text = (TextView) dialogView.findViewById(R.id.make_sure_text);

        money_amount_text.setText(money_text.getText().toString().trim());
        df   = new DecimalFormat("######0.00");

        if (isFirstFree){
            money_describe_text.setVisibility(View.GONE);
            money_practice_amount_text.setVisibility(View.GONE);
        }else {
            money_describe_text.setVisibility(View.VISIBLE);
            money_practice_amount_text.setVisibility(View.VISIBLE);
            //手续费
            double moneyCharge = Arith.mul(extractMonry, 0.005);
            money_describe_text.setText(String.format(getResources().getString(R.string.money_charge_describe), df.format(moneyCharge) +""));
            //实际到账
            double moneyPractice = Arith.sub(extractMonry, moneyCharge);
            money_practice_amount_text.setText(String.format(getResources().getString(R.string.money_practice_amount), df.format(moneyPractice) +""));
        }

        // 对话框
        final Dialog dialog = new Dialog(getActivity(), R.style.MyDialogStyle);
        //点击区域外消除
//        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        dialog.getWindow().setContentView(dialogView);
        //取消
        cancle_text.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        //确认提现
        make_sure_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPasswordDialog();
                dialog.dismiss();
            }
        });

    }

    /**
     * 提现输入密码框
     */
    private void showPasswordDialog(){
        LayoutInflater factory = LayoutInflater.from(getActivity());
        final LinearLayout dialogView = (LinearLayout) factory.inflate(
                R.layout.dialog_extract_money, null);
        //密码输入框
        final ClearEditText extract_money_edit = (ClearEditText) dialogView.findViewById(R.id.extract_money_edit);
        //取消
        final LinearLayout linear_cancel = (LinearLayout) dialogView.findViewById(R.id.linear_cancel);
        //确定
        final LinearLayout linear_make_sure = (LinearLayout) dialogView.findViewById(R.id.linear_make_sure);

        // 对话框
        final Dialog dialog = new Dialog(getActivity(), R.style.MyDialogStyle);
        //点击区域外消除
//        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        dialog.getWindow().setContentView(dialogView);
        //取消
        linear_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        //确定
        linear_make_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    extractMoney("D", "RSA", money_text.getText().toString(), extract_money_edit.getText().toString().trim(),
                            SubmitCaseContent(), bankMessage.getNo_agree(), "1");

                dialog.dismiss();
            }
        });

    }

    private List<HashMap<String, String>> hashMapLists;
    /**
     * 风控参数
     * @return
     */
    public String SubmitCaseContent() {
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String content = "";
        if (hashMapLists == null)
            hashMapLists = new ArrayList<>();
        if (hashMapLists.size() > 0)
            hashMapLists.clear();

        HashMap<String, String> map = new HashMap<>();
        map.put("user_info_dt_register",df.format(new Date()));

        hashMapLists.add(map);

        if (hashMapLists == null) {
            return "";
        }
        StringBuilder mStringBuilder = new StringBuilder();

        for (int i = 0; i < hashMapLists.size(); i++) {
            String hashMapToJson = JsonUtils.hashMapToJson(hashMapLists.get(i));
            mStringBuilder.append(hashMapToJson).append(",");
        }
        if (mStringBuilder.length() > 0) {
            String substring = mStringBuilder.toString().substring(0, mStringBuilder.toString().lastIndexOf(","));
            content = substring;
        } else {
//            showShortToast("供应信息不能为空");
        }
        return content;
    }

    /**
     * 提现--个人
     * @param sign_type RSA
     * @param money_order 提现金额
     * @param pwd_pay 提现密码
     * @param risk_item 风控参数
     * @param no_agree 签约协议号
     * @param paytime_type 1、 实时提现 2、 普通提现 3、 T+1 提现 默认 2 普通提现
     */
    public void extractMoney(String pay_type, String sign_type, String money_order, String pwd_pay, String risk_item, String no_agree, String paytime_type) {
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
//        mSendCodeHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        mSendCodeHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        mSendCodeHashMap.put("money_order", money_order);
        mSendCodeHashMap.put("sign_type", sign_type);
        mSendCodeHashMap.put("pwd_pay", pwd_pay);
        mSendCodeHashMap.put("risk_item", risk_item);
        mSendCodeHashMap.put("no_agree", no_agree);
        mSendCodeHashMap.put("paytime_type", paytime_type);
        mSendCodeHashMap.put("pay_type", pay_type);

        LogUtils.e("mSendCodeHashMap", mSendCodeHashMap.toString());
        //post 传参
        paramMaps.put("money_order", money_order);
        paramMaps.put("sign_type", sign_type);
        paramMaps.put("pwd_pay", pwd_pay);
        paramMaps.put("risk_item", risk_item);
        paramMaps.put("no_agree", no_agree);
        paramMaps.put("paytime_type", paytime_type);
        paramMaps.put("pay_type", pay_type);

        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        LogUtils.e("mSendCodeHashMap", SignUtil.getInstance().getSign(mSendCodeHashMap));
        HttpClient.post(OkeHomeConsumptionApi.WALLET_BANK_EXTRACT_MONEY, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    LogUtils.e("content_提现", "content=" + content);
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        JSONObject jsonObject = jsonOBJ.optJSONObject("data");
                        JSONObject data = jsonObject.optJSONObject("data");
                        String ret_code = data.optString("ret_code");
                        String ret_msg = data.optString("ret_msg");
                        if ("0000".equals(ret_code)){
                           showShortToast("提现成功");
                            setFragmentResult(RESULT_OK,new Bundle());
                            _mActivity.onBackPressed();
                        }else {
                            showShortToast(ret_msg);
                        }

                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    }
                } catch (Exception ex) {
                    LogUtils.e("DresserPartnerRegisterPost", "失败 ");
                }
            }

            @Override

            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }

    /**
     * 是否是首次提现
     */
    public void isFirstFree() {
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
//        mSendCodeHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        mSendCodeHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mSendCodeHashMap.put("client", Constants.CLIENT);

        LogUtils.e("mSendCodeHashMap", mSendCodeHashMap.toString());

        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        LogUtils.e("mSendCodeHashMap", SignUtil.getInstance().getSign(mSendCodeHashMap));
        HttpClient.post(OkeHomeConsumptionApi.IS_FIRST_FREE, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("content_判断个人钱包用户是否是本周首次提现", "content=" + content);

                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        JSONObject jsonObject = jsonOBJ.optJSONObject("data");
                        isFirstFree = jsonObject.optBoolean("success");
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    }
                } catch (Exception ex) {
                    LogUtils.e("DresserPartnerRegisterPost", "失败 ");
                }
            }

            @Override

            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }

    /**
     * 获取银行卡列表
     * @param user_id 用户编号
     * @param sign_type RSA
     */
    public void getBankList(String user_id, String sign_type) {
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
//        mSendCodeHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        mSendCodeHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        mSendCodeHashMap.put("user_id", user_id);
        mSendCodeHashMap.put("sign_type", sign_type);

        LogUtils.e("mSendCodeHashMap", mSendCodeHashMap.toString());
        //post 传参
        paramMaps.put("user_id", user_id);
        paramMaps.put("sign_type", sign_type);

        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        LogUtils.e("mSendCodeHashMap", SignUtil.getInstance().getSign(mSendCodeHashMap));
        HttpClient.post(OkeHomeConsumptionApi.WALLET_BANKLIST, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    LogUtils.e("content_获取银行卡列表", "content=" + content);
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        JSONObject jsonObject = jsonOBJ.optJSONObject("data");
                        JSONObject data = jsonObject.optJSONObject("data");
                        JSONArray jsonArray = data.optJSONArray("agreement_list");
                        String ret_code = data.optString("ret_code");
                        if ("0000".equals(ret_code)){
//                            mBankMessageList = com.alibaba.fastjson.JSONArray.parseArray(jsonArray.toString(), BankMessage.class);
//                            bankname_text.setText(mBankMessageList.get(0).getBank_name());
//                            bankno_text.setText("**** **** **** " + mBankMessageList.get(0).getCard_no());
                        }

                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    }
                } catch (Exception ex) {
                    LogUtils.e("DresserPartnerRegisterPost", "失败 ");
                }
            }

            @Override

            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }
}
